package com.superdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * ClassName: RedisIdWorker
 * Package: com.superdp.utils
 * Description:
 *
 * @Author: XKing
 * @Create: 2023/7/3 - 14:44
 * @Version: 1.0
 */
@Component
public class RedisIdWorker {
    private StringRedisTemplate stringRedisTemplate;

    ////初始时间戳2022年1月1日
    private static final long BEGIN_TIMESTAMP=1640995200L;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String prefix){
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp=nowSecond-BEGIN_TIMESTAMP;
        //2.生成序列号
        //2.1获取当前时间精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //2.2每天的订单都从0开始，可以统计每天的订单数量
        Long count = stringRedisTemplate.opsForValue().increment("incr:" + prefix + ":" + date);
        return timeStamp<<32|count;
    }

    /**
     * 初始时间戳
     */
//    public static void main(String[] args) {
//        LocalDateTime time = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
//        long BEGINTIMESTAMP = time.toEpochSecond(ZoneOffset.UTC);
//        System.out.println(BEGINTIMESTAMP);//1640995200
//    }
}
